/**
 * Copyright 2018 orivil.com. All rights reserved.
 * Use of this source code is governed by a MIT-style
 * license that can be found at https://mit-license.org.
 */

package model

import (
	"time"
	"gitee.com/tugoer/psy-testing/code/env"
)

type Subject struct {
	ID          int    `json:"id"`
	OriginalID  string `json:"original_id" gorm:"unique_index"`
	Title       string `json:"title" gorm:"index"`
	Logo        string `json:"logo"`
	Description string `json:"desc"`
	// json 格式数据
	Questions string `json:"question" gorm:"type:TEXT"`
	// 1：单一问题，按选项 key 获得结果
	// 2：按 weight 获得结果
	// 3：按 next 获得结果
	Type int `json:"type" gorm:"index"`
	// 主题类型
	Cid       int        `json:"cid" gorm:"index"`
	Img       string     `json:"img"`
	View      int        `json:"view" gorm:"index"`
	Top       int        `json:"top" gorm:"index"`
	LikeNum   int        `json:"like_num" gorm:"index"`
	CreatedAt *time.Time `json:"created_at" gorm:"index"`
	UpdatedAt *time.Time `json:"updated_at"`
}

func (s *Subject) Create() error {
	if s.CreatedAt == nil {
		now := time.Now()
		s.CreatedAt = &now
	}
	return env.GormDB.Create(s).Error
}

func (s *Subject) Update() error {
	return env.GormDB.Model(s).Updates(s).Error
}

func DeleteSubject(originalID string) error {
	return env.GormDB.Where("original_id = ?", originalID).Delete(Subject{}).Error
}

func GetSubject(subjectID string) (subject *Subject, err error) {
	subject = &Subject{}
	err = env.GormDB.First(subject, "original_id = ?", subjectID).Error
	return
}

func GetLastSubject() (subject *Subject) {
	subject = &Subject{}
	env.GormDB.Last(subject)
	if subject.ID > 0 {
		return subject
	} else {
		return nil
	}
}

// 获取列表数据时需要查询的字段
var ListField = []string{"original_id", "title", "img", "description", "view"}

func SelectSubjects(order string, limit, offset int, field []string) (ss []*Subject, err error) {
	errs := env.GormDB.Select(field).Order(order).Offset(offset).Limit(limit).Find(&ss).GetErrors()
	for _, err := range errs {
		if err != nil {
			return nil, err
		}
	}
	return
}

func SearchSubjects(title string) (ss []*Subject, err error) {
	errs := env.GormDB.Where("title LIKE ?", "%"+title+"%").Select(ListField).Limit(20).Find(&ss).GetErrors()
	for _, err := range errs {
		if err != nil {
			return nil, err
		}
	}
	return
}

func SelectLatestSubs(limit, offset int) (ss []*Subject, err error) {
	return SelectSubjects("id desc", limit, offset, ListField)
}

func SelectHottestSubs(limit, offset int) (ss []*Subject, err error) {
	return SelectSubjects("view desc", limit, offset, ListField)
}

func SelectRecommendSubs(limit, offset int) (ss []*Subject, err error) {
	return SelectSubjects("top desc", limit, offset, ListField)
}
